package com.terrace.web.shiro;

import org.apache.commons.lang.ObjectUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.terrace.core.utils.PasswordUtils;

/**
 * 自定义Shiro密码验证
 * @author jiangyg
 *
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {
	
	private static final Logger logger = LoggerFactory.getLogger(CustomCredentialsMatcher.class);

	@Override
	public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo authInfo) {
		try {
			UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
			SimpleAuthenticationInfo info = (SimpleAuthenticationInfo) authInfo;
			// 用户原密码
			String realPwd = ObjectUtils.toString(info.getCredentials());
			// 用户输入的密码明文
			String inputPwd = String.valueOf(token.getPassword());
			// 用户登陆账号
			String userAccount = ObjectUtils.toString(token.getUsername());
			// 用户私钥盐
			ByteSource byteSource = info.getCredentialsSalt();
			// 加完密之后的密码
			String ciphertext = PasswordUtils.encrypt(userAccount, inputPwd, byteSource.getBytes());
			return equals(ciphertext, realPwd);
		} catch (Exception e) {
			logger.error("用户登录密码验证出错：", e);
			return false;
		}
	}
	
}
